package com.qclix.inv.webservice;

import com.qclix.inv.Client;
import com.qclix.inv.InvoiceService;
import com.qclix.inv.InvoiceServiceException;
import com.qclix.inv.xml.XMLClient;
import com.qclix.inv.xml.XMLtoDomainTranslator;
import org.springframework.ws.server.endpoint.AbstractMarshallingPayloadEndpoint;

/**
 * TODO: Some javadoc maybe ?
 */
public class NewClientMarshallingEndPoint extends AbstractMarshallingPayloadEndpoint {

    private InvoiceService invoiceService;
    private XMLtoDomainTranslator xmlToDomainTranslator;

    public void setXmlToDomainTranslator(XMLtoDomainTranslator xmlToDomainTranslator) {
        this.xmlToDomainTranslator = xmlToDomainTranslator;
    }

    public void setInvoiceService(InvoiceService invoiceService) {
        this.invoiceService = invoiceService;
    }

    @Override
    protected Object invokeInternal(Object o) throws Exception {
        NewClientRequest request = (NewClientRequest) o;
        System.out.println("request = " + request);
        XMLClient xmlClient = request.getClient();
        System.out.println("Received request to create client " + xmlClient);
        try {
            Client newClient = xmlToDomainTranslator.getDomainVersion(xmlClient);
            invoiceService.addClient(newClient);
            NewClientResponse response = new NewClientResponse();
            response.setClientId(newClient.getId());
            return response;
        } catch (InvoiceServiceException e) {
            NewClientException exception = new NewClientException();
            exception.setErrorCode("TO BE SET"); // set the proper exception
            return exception;
        }
    }
}
